#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/18 9:20
# @Author  : lizhen
# @Site    : 
# @File    : Zhihu.py
# @Software: PyCharm
import os
import requests
import time
import pytesseract
from PIL import Image
import numpy as np

base_dir = './ext/Zhihu/'


class ZhihuDemo:
    def save_img(self, data, filename='zhihu.jpg'):
        with open(base_dir + filename, 'wb') as fp:
            fp.write(data)

    def clear_border(self, img):
        # 去除边框
        w, h = img.shape
        for x in range(w):
            for y in range(h):
                if x < 2 or x > w - 2 or y < 2 or y > h - 2:
                    img[x, y] = 255
        return img

    def binarization(self, image, threshold=128):
        # 二值化
        w, h = image.shape
        for x in range(w):
            for y in range(h):
                if image[x, y] <= threshold:
                    image[x, y] = 0
                else:
                    image[x, y] = 255
        return image

    def captcha(self):
        # 验证码识别
        files = os.listdir(base_dir)
        for item in files[1:2]:
            # 灰度化
            im = np.array(Image.open(base_dir + item).convert('L'))
            im = self.clear_border(im)
            im = self.binarization(im)
            im = Image.fromarray(im, mode='L')
            im.show()
            text = pytesseract.image_to_string(im, 'fontlz')
            print("{{image_name:{},result:{}}}".format(item, text))

    def _test_save_img(self):
        """
        zd = ZhihuDemo()
        zd._test_save_img()
        """
        # 构建一个保存Cookie值的session对象
        session = requests.Session()
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'}
        # 先获取页面信息，找到需要POST的数据（并且已记录当前页面的Cookie）
        html = session.get('https://www.zhihu.com/#signin', headers=headers).content
        # 取出验证码，r后面的值是Unix时间戳,time.time()
        captcha_url = 'https://www.zhihu.com/captcha.gif?r=%d&type=login' % (time.time() * 1000)
        response = session.get(captcha_url, headers=headers)
        self.save_img(response.content)

    def _test_captcha(self):
        """
        zd = ZhihuDemo()
        zd._test_captcha()
        """
        self.captcha()


if __name__ == "__main__":
    zd = ZhihuDemo()
    zd._test_captcha()
